<template>
	<view class="view-fiex">
		<!-- 头部内容 -->
		<view class="header">
			<view class="vrow flex-items-center">
				<image src="../../static/logo.png" class="logo" />
				<view class="flex-column">
					<view class="flex flex-items-center" @click="showShop">
						<view class="f40 title blod">
							<text>{{config.appName}}</text>
						</view>
						<view class="icon-info">
							<uni-icons type="down" color="#fff"></uni-icons>
						</view>
					</view>
					<view class="multi_line">{{config.appDesc}}</view>
				</view>
			</view>
			<view class="vline"></view>
			<view class="flex flex-column flex-center" style="margin-right: 30rpx;" @click="showPayNumber">
				<image src="../../static/pay.png" class="payqrcode" />
				<text class="f24 tc">付款</text>
			</view>
		</view>
		<lgd-tab class="view-body" :tabValue="tabValue" :tabIndex="tabIndex" @getIndex="getIndex" textColor="#333"
			underlineColor="#333" />
		<msgList v-show="tabIndex == 0" ref="msgRef"></msgList>
		<template v-if="tabIndex == 1">
			<view class="header-msg">
				<view class="flex flex-items-center">
					<uni-icons class="mr10" size="24" color="#FFA459" type="info"></uni-icons>
					<text class="f30">定点取货免配送费</text>
				</view>
				<view class="flex flex-items-center">
					<uni-icons class="mr10" size="24" color="#2d8cf0" type="cart"></uni-icons>
					<text class="f30 blue" @click="gotoOrder">我的订单</text>
				</view>
			</view>
			<!-- 列表 -->
			<view class="flex-1 ovh">
				<mo-product-list open-tag v-if="list && list.length > 0" :tagKey="tagKey" :list="list"
					@scrollEnd="scrollEnd">
					<template v-slot:header="{item}">
						<view class="title">{{item.name}}</view>
					</template>
					<template v-slot="{item}">
						<product-item v-for="(child, childIndex) in item.list" :key="childIndex" :item="child"
							:name="item.name" @onShowDetail="showDetail" @onChange="onChange"></product-item>
					</template>
				</mo-product-list>
			</view>
			<!-- 底部按钮 -->
			<product-bottom :list="cartList">
				<template v-slot:header="{list}">
					<view class="tp-info">
						<view class="">商品</view>
						<view class="" @click="clearCart">清空购物车</view>
					</view>
				</template>
				<template v-slot:popItem="{item}">
					<product-item v-for="(child, childIndex) in item.list" :key="childIndex" :item="child"
						:name="item.name" @onChange="onChange"></product-item>
				</template>
			</product-bottom>
		</template>

		<productDetail ref="productDetailRef" @onChange="onChange"></productDetail>
		<shopDetail ref="shopDetailRef" :config="config"></shopDetail>
		<payPage ref="payPageRef"></payPage>
	</view>
</template>

<script>
	import {
		shopCode,
		baseUrl
	} from '@/pages/common/js/http.js'
	import {
		getConfig,
		SelectListCategory,
		SelectListProduct,
		getOpenid
	} from '@/pages/common/api.js'
	import moProductList from "@/components/mo-product-list/mo-product-list.vue";
	import productItem from './product-item.vue'
	import productBottom from './product-bottom.vue'
	import productDetail from "./product-detail.vue";
	import shopDetail from "./shop-detail.vue";
	import payPage from "./pay.vue";
	import msgList from "./msg.vue";
	export default {
		components: {
			moProductList,
			productItem,
			productBottom,
			productDetail,
			shopDetail,
			payPage,
			msgList
		},
		data() {
			return {
				list: [],
				tagKey: 'tag',
				tabIndex: 1,
				tabValue: [`动态`, `下单`],
				config: {}
			}
		},
		computed: {
			cartList() {
				const ls = JSON.parse(JSON.stringify(this.list))
				return ls.reduce((t, item) => {
					const child = item.list.filter(el => {
						return !!el.selected
					})
					if (child.length) {
						t.push({
							...item,
							list: child
						})
					}
					return t
				}, [])
			}
		},
		onPullDownRefresh() {
			console.log('下拉更新')
			if (this.tabIndex == 0) {
				this.$refs.msgRef.reload = true
				this.$refs.msgRef.search();
			} else {
				this.loadProduct()
			}
		},
		onLoad() {
			let config = uni.getStorageSync('config')
			console.log('config', config)
			if (config) {
				this.config = config
			}
			// 微信登录
			this.loginHandle()
			this.loadData()
			this.loadProduct()
			this.initData();
			console.log('清空购物车事件')
			uni.$off('refresh-list')
			uni.$on('refresh-list', () => {
				console.log('清空购物车')
				this.clearCart()
				this.loadProduct()
			})
		},
		methods: {
			getNickName() {
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.userInfo']) {
							// 用户未授权，可以引导用户去授权
							wx.authorize({
								scope: 'scope.userInfo',
								success() {
									// 用户已授权，可以再次调用 wx.getUserProfile 获取用户信息
									wx.getUserProfile({
										desc: '用于完善用户信息', // 声明获取用户个人信息后的用途
										success: (res) => {
											console.log('用户:', res.userInfo);
											uni.setStorageSync('config-nickname', res.userInfo
												.nickName)
										},
										fail: (err) => {
											console.error('用户拒绝授权:', err);
										}
									});
								},
								fail() {
									// 用户拒绝授权，可以引导用户手动打开设置页进行授权
									wx.openSetting();
								}
							});
						} else {
							// 用户已授权，直接调用 wx.getUserProfile 获取用户信息
							wx.getUserProfile({
								desc: '用于完善用户信息', // 声明获取用户个人信息后的用途
								success: (res) => {
									console.log('用户:', res.userInfo);
									uni.setStorageSync('config-nickname', res.userInfo.nickName)
								},
								fail: (err) => {
									console.error('用户拒绝授权:', err);
								}
							});
						}
					}
				});
			},
			loginHandle() {
				let that = this
				uni.login({
					provider: 'weixin',
					success: (res) => {
						if (res.code) {
							// 将 code 发送到后端
							getOpenid({
								code: res.code
							}).then(response => {
								console.log('微信登录', response)
								const openid = response.data;
								uni.setStorageSync('config-openid', openid)
								let nickName = uni.getStorageSync('config-nickname')
								console.error('微信昵称:', nickName);
								if (!nickName) {
									uni.showModal({
										title: '授权',
										content: '用于完善用户信息，需获取微信昵称？',
										success(res) {
											if (res.confirm) {
												that.getNickName()
											}
										}
									});
								}
							})
						} else {
							console.error('登录失败', res.errMsg);
						}
					}
				});
			},
			getMyKey(key) {
				return `${shopCode}_${key}`
			},
			loadProduct() {
				let basePath = baseUrl()
				SelectListCategory({
					shopCode
				}).then(res => {
					console.log('SelectListCategory', res)
					if (res.code === 20000) {
						let types = res.data.map(d => d.name)
						SelectListProduct({
							shopCode
						}).then(res => {
							console.log('SelectListProduct', res)
							uni.stopPullDownRefresh()
							this.list = types.map(d => {
								let list = res.data.filter(dd => dd.categoryName == d).map(dd => {
									dd.image =
										`${basePath}/open-api/product/img?refId=${dd.id}`
									return dd
								})
								return {
									name: d,
									list
								}
							})
						})
					}

				})

			},
			loadData() {
				getConfig({
					codes: [
						this.getMyKey('appName'),
						this.getMyKey('appDesc'),
						this.getMyKey('phone'),
						this.getMyKey('wechat'),
						this.getMyKey('address'),
						this.getMyKey('lng'),
						this.getMyKey('lat'),
						this.getMyKey('deliveryFee'),
						this.getMyKey('placeList'),
					].join(',')
				}).then((res) => {
					console.log('getConfig', res)
					if (res.code === 20000) {
						let form = {}
						res.data.forEach((d) => {
							form[d.code] = d.value
						})
						this.config.appName = form[this.getMyKey('appName')] || ''
						this.config.appDesc = form[this.getMyKey('appDesc')] || ''
						this.config.phone = form[this.getMyKey('phone')] || ''
						this.config.wechat = form[this.getMyKey('wechat')] || ''
						this.config.address = form[this.getMyKey('address')] || ''
						this.config.lng = form[this.getMyKey('lng')] || ''
						this.config.lat = form[this.getMyKey('lat')] || ''
						this.config.deliveryFee = form[this.getMyKey('deliveryFee')] || ''
						let placeList = form[this.getMyKey('placeList')] || ''
						if (placeList) {
							this.config.placeList = placeList.split(',')
						}
						// 存储
						uni.setStorageSync('config', this.config)
					}
				})
			},
			showPayNumber() {
				this.$refs.payPageRef.showDetail()
			},
			gotoOrder() {
				uni.navigateTo({
					url: `/pages/order/index`
				});
			},
			showDetail(row) {
				this.$refs.productDetailRef.showDetail(row)
			},
			showShop() {
				this.$refs.shopDetailRef.showDetail()
			},
			getIndex(e) {
				console.log(e)
				this.tabIndex = e
			},
			scrollEnd(e) {
				console.log(e)
			},
			async onChange(item) {
				console.log('选择了')
				await this.updateSelect(item)
				await this.updateTag()
			},
			async initData() {
				await this.updateTag()
				await uni.stopPullDownRefresh();
			},
			updateTag() {
				return new Promise((resole, reject) => {
					this.$nextTick(function() {
						this.list.forEach((el, i) => {
							const tag = el.list.reduce((t, c) => {
								t = c.selected ? t + c.selected : t
								return t
							}, 0)
							const obj = {
								...el,
								[this.tagKey]: tag
							}
							this.$set(this.list, i, obj)
						})
					})
					resole()
				})
			},
			updateSelect({
				name,
				item
			}) {
				return new Promise((resole, reject) => {
					this.$nextTick(function() {
						this.list.forEach((el, index) => {
							if (el.name == name) {
								el.list.forEach((e, i) => {
									if (e.name == item.name) {
										const obj = {
											...e,
											...item
										}
										this.$set(el.list, i, obj)
									}
								})
								this.$set(this.list, index, {
									...el
								})
							}
						})
						resole()
					})
				})
			},
			async clearCart() {
				this.list.forEach((el, index) => {
					el.list.forEach((e, i) => {
						if (e.selected) {
							const obj = {
								...e,
								selected: 0
							}
							this.$set(el.list, i, obj)
						}
					})
					this.$set(this.list, index, {
						...el
					})
				})
				await this.updateTag()
			},
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background: #f8f8f8;
	}

	.view-fiex {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: calc(100vh - constant(safe-area-inset-bottom));
		height: calc(100vh - env(safe-area-inset-bottom));
		/* #ifndef MP-WEIXIN */
		height: calc(100vh - 44px - constant(safe-area-inset-bottom));
		height: calc(100vh - 44px - env(safe-area-inset-bottom));
		/*  #endif  */
	}

	.flex-1 {
		flex: 1;
	}

	.ovh {
		overflow: hidden;
	}

	.title {
		padding: 30rpx;
	}

	.innor {
		margin-left: 20rpx;
		margin-right: 20rpx;
	}

	.tp-tips {
		text-align: center;
		background-color: #f9ede3;
		font-size: 24rpx;
		padding: 12rpx 0;
	}

	.tp-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #eee;
		padding: 15rpx 30rpx;
		font-size: 28rpx;
		color: gray;
	}

	.header {
		background: linear-gradient(90deg, #FFA459, #F07F23);
		color: #fff;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		padding-bottom: 60rpx;
		padding-top: 150rpx;

		.title {
			padding: 10rpx 0;
		}
	}

	.header-msg {
		padding: 20rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.logo {
		width: 130rpx;
		height: 130rpx;
		flex-shrink: 0;
		border-radius: 50%;
		margin-left: 30rpx;
		margin-right: 30rpx;
	}

	.payqrcode {
		width: 50rpx;
		height: 50rpx;
	}

	.view-body {
		border-top-right-radius: 30rpx;
		border-top-left-radius: 30rpx;
		overflow: hidden;
		margin-top: -30rpx;
		z-index: 100;
	}

	.icon-info {
		margin-left: 20rpx;
		background-color: rgba(250, 250, 250, 0.4);
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
		line-height: 50rpx;
		text-align: center;
	}
</style>